package com.poly.common.database.handle;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.poly.common.core.enums.DelFlag;
import com.poly.common.security.utils.SecurityUtils;
import com.poly.system.model.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

/**
 * 数据填充
 * 需要再字段增加 @TableField(value = "`xx`", fill = FieldFill.INSERT) 注解
 *
 * @author QingYu Chen
 */
@Component
public class DataFillHandle implements MetaObjectHandler {
    private static final String FIELD_NAME = "deptId";
    private static final String CREATE_BY = "createBy";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_BY = "updateBy";
    private static final String UPDATE_TIME = "updateTime";
    private static final String DEL_FLAG = "delFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, FIELD_NAME, Long.class, getDeptId());
        this.strictInsertFill(metaObject, CREATE_BY, Long.class, getUserId());
        this.strictInsertFill(metaObject, CREATE_TIME, Date.class, new Date());
        this.strictInsertFill(metaObject, DEL_FLAG, Integer.class, DelFlag.normal.getValue());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, FIELD_NAME, Long.class, getDeptId());
        this.strictUpdateFill(metaObject, UPDATE_BY, Long.class, getUserId());
        this.strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
    }

    public Long getDeptId() {
        return getLoginUser().map(LoginUser::getDeptId).orElse(0L);
    }

    public Long getUserId() {
        return getLoginUser().map(LoginUser::getUserid).orElse(0L);
    }

    public Optional<LoginUser> getLoginUser() {
        try {
            return Optional.ofNullable(SecurityUtils.getLoginUser());
        } catch (Exception e) {
            return Optional.empty();
        }
    }

}
